package com.fhnew.app.ui.activity.userinfo.fragment.yue;

import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.fhnew.app.R;
import com.fhnew.app.model.internet.been.B_ThirdMoneyList;
import com.fhnew.app.model.internet.model.ThirdGameModel;
import com.fhnew.app.model.internet.model.UserModel;
import com.fhnew.app.ui.activity.userinfo.FragmentDataChang;
import com.fhnew.app.ui.activity.userinfo.PageDataChangeControl;
import com.fhnew.app.widget.LoadingDialog;

import java.util.ArrayList;
import java.util.List;

import static android.content.Context.INPUT_METHOD_SERVICE;

/**
 * 余额转入
 */
public class ChargeMoneyFragment extends Fragment implements FragmentDataChang {

    private PageDataChangeControl pageDataChangeControl;
    private String conentTag;

    private Bundle bundle;

    @Override
    public void setListener (PageDataChangeControl pageDataChangeControl) {
        this.pageDataChangeControl = pageDataChangeControl;
    }

    @Override
    public void dataChanged (Bundle bundle) {
        this.bundle = bundle;

        conentTag = bundle.getString("conentTag");
        //当从对话框返回的情况
        if (bundle.getBoolean("isBack")) {
            if(bundle.getBoolean("finish")){
                thirdAdapter.setGame_id(-1);
                inputPrice.setText("");
                loadingDialog.showLoading();
                int gameId = bundle.getInt("game_id");
                if(gameId == 0){
                    thirdGameModel.refreshMyMoney();
                }else{
                    thirdGameModel.getMoney(gameId, true);
                }
            }
            bundle.putBoolean("finish",false);
            bundle.putBoolean("isBack",false);
        }else{
            bundle.putInt("game_id",-1);
            initInfoView();
        }


    }

    //=================================================================
    //
    //=================================================================

    private Button title;
    private TextView tips;
    private Button press;
    private RecyclerView thiredList;
    private ThirdAdapter thirdAdapter;
    private LoadingDialog loadingDialog;
    private EditText inputPrice;

    private Button charge;

    private void initView (View view) {

        loadingDialog = new LoadingDialog((ViewGroup) view);
        loadingDialog.setDialogCancelable(false);
        loadingDialog.setShowTips(false);
        loadingDialog.showLoading();

        title = view.findViewById(R.id.button_Yue_Charge_Title);
        tips = view.findViewById(R.id.textView_Yue_Charge_Tips);
        press = view.findViewById(R.id.button_Yue_Charge_Press);

        thiredList = view.findViewById(R.id.recyclerView_YuE_ChargeList);
        thiredList.setLayoutManager(new GridLayoutManager(getContext(), 3));
        thirdAdapter = new ThirdAdapter();
        thirdAdapter.setOnItemClickListener(onItemClickListener);
        thiredList.addItemDecoration(itemDecoration);
        thiredList.setAdapter(thirdAdapter);

        charge = view.findViewById(R.id.button_Yue_Charge_Press);
        charge.setOnClickListener(onClickListener);

        inputPrice = view.findViewById(R.id.editText_YuE_InputPrice);
    }

    private void initInfoView () {
        if (title == null) return;

        if (conentTag.equals("1")) {
            title.setText("转入");
            tips.setText("请选择转入平台");
            press.setText("一键转入");
            thirdAdapter.setGame_id(-1);
            inputPrice.setText("");
        } else if (conentTag.equals("2")) {
            title.setText("转出");
            tips.setText("请选择转出平台");
            press.setText("一键转出");
            thirdAdapter.setGame_id(-1);
            inputPrice.setText("");
        }  else {
            thirdAdapter.setGame_id(-1);
            inputPrice.setText("");
            title.setText("null");
        }
        thirdAdapter.notifyDataSetChanged();
    }

    private RecyclerView.ItemDecoration itemDecoration = new RecyclerView.ItemDecoration() {
        @Override
        public void getItemOffsets (@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.left = 10;
            outRect.top = 10;
            outRect.right = 10;
            outRect.bottom = 10;
        }
    };

    @Nullable
    @Override
    public View onCreateView (@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        container = (ViewGroup) inflater.inflate(R.layout.fragment_yue_charge, null);
        initView(container);
        initInfo();
        return container;
    }

    @Override
    public void onResume () {
        super.onResume();
        initInfoView();
    }

    @Override
    public void onDestroy () {
        super.onDestroy();
        thirdGameModel.unregistThirdGameMoneyChangedListener(thirdGameMoneyChangedListener);
        userModel.unRegistListener(userInformationChanged);
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick (View v) {
            int game_id = thirdAdapter.getGame_id();
            if (game_id < 0) {
                Toast.makeText(getContext(), "请求选择平台", Toast.LENGTH_SHORT).show();
                return;
            }

            InputMethodManager imm = (InputMethodManager) getContext().getSystemService(INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(inputPrice.getWindowToken(), 0);

            String money = inputPrice.getText().toString();
            if (money.isEmpty()) {
                Toast.makeText(getContext(), "请输入金额", Toast.LENGTH_SHORT).show();
                return;
            }

            bundle.putInt("price", Integer.parseInt(money));
            bundle.putString("type", conentTag);
            bundle.putInt("game_id", game_id);
            bundle.putString("token", userModel.getToken());
            bundle.putString("name", thirdAdapter.getM_GameName());
            pageDataChangeControl.changeFragmemt("YuE_01", bundle);
        }
    };

    private ThirdGameModel.ThirdGameMoneyChangedListener thirdGameMoneyChangedListener = new ThirdGameModel.ThirdGameMoneyChangedListener() {
        @Override
        public void myMoneyChanged (){
            if(bundle.getInt("game_id") == 0) {
                loadingDialog.dismiss();
                thirdAdapter.setUserMoney(Float.parseFloat(userModel.getUser().getMoney()));
            }
        }

        @Override
        public void allThirdGameMoneyChanged () {
            B_ThirdMoneyList b_thirdMoneyList = thirdGameModel.getThirdGameList();
            if (b_thirdMoneyList != null) {
                loadingDialog.dismiss();
                thirdAdapter.setThirdMoneyList(b_thirdMoneyList);
            }
        }

        @Override
        public void thirdGameMoneyChanged (int game_id) {
            loadingDialog.dismiss();
            thirdAdapter.setThirdMoneyList(thirdGameModel.getThirdGameList());
        }
    };

    private UserModel.UserInformationChanged userInformationChanged = new UserModel.UserInformationChanged() {
        @Override
        public void userInformationChanged () {
            thirdAdapter.setUserMoney(Float.parseFloat(userModel.getUser().money));
        }
    };

    private ThirdAdapter.OnItemClickListener onItemClickListener = new ThirdAdapter.OnItemClickListener() {
        @Override
        public void onItem (int game_id) {

        }
    };

    //=============================================================
    // Model
    //=============================================================

    private ThirdGameModel thirdGameModel;
    private UserModel userModel;

    private void initInfo () {
        thirdGameModel = ThirdGameModel.getInstance(getContext());
        thirdGameModel.registThirdGameMoneyChangedListener(thirdGameMoneyChangedListener);
        B_ThirdMoneyList thirdGameList = thirdGameModel.getThirdGameList();
        thirdAdapter.setThirdMoneyList(thirdGameList);
        if (thirdGameList == null) {
            thirdGameModel.refreshAllThirdMoney();
        } else {
            loadingDialog.dismiss();
        }

        userModel = UserModel.getInstance(getContext());
        userModel.registListener(userInformationChanged);
        thirdAdapter.setUserMoney(Float.parseFloat(userModel.getUser().money));
    }


    //=============================================================
    //  列表适配器
    //=============================================================
    private static class ThirdAdapter extends RecyclerView.Adapter<ThirdAdapter.ViewHolder> {

        private int game_id = -1;
        private String m_GameName;

        private OnItemClickListener onItemClickListener;

        private List<B_ThirdMoneyList.DataBean> dataBeans;
        private B_ThirdMoneyList thirdMoneyList;
        private float money;

        public ThirdAdapter () {
            dataBeans = new ArrayList<>();
        }

        public int getGame_id () {
            return game_id;
        }

        public void setGame_id (int game_id) {
            this.game_id = game_id;
        }

        public void setThirdMoneyList (B_ThirdMoneyList thirdMoneyList) {
            this.thirdMoneyList = thirdMoneyList;
            setData();
        }

        public void setUserMoney (float money) {
            this.money = money;
            setData();
        }

        public String getM_GameName () {
            return m_GameName;
        }

        public void setM_GameName (String m_GameName) {
            this.m_GameName = m_GameName;
        }

        private void setData () {
            dataBeans.clear();

            if (money != 0) {
                B_ThirdMoneyList.DataBean dataBean = new B_ThirdMoneyList.DataBean();
                dataBean.setName("账户余额");
                dataBean.setMoney(money);
                dataBean.setGame_id(0);
                dataBeans.add(dataBean);
            }

            if (thirdMoneyList != null) {
                dataBeans.addAll(thirdMoneyList.getData());
            }
            notifyDataSetChanged();
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder (@NonNull ViewGroup viewGroup, int i) {
            viewGroup = (ViewGroup) LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_third, null);
            return new ViewHolder(viewGroup);
        }

        @Override
        public void onBindViewHolder (@NonNull ViewHolder viewHolder, int i) {

            B_ThirdMoneyList.DataBean dataBean = dataBeans.get(i);

            viewHolder.touchView.setTag(dataBean.getGame_id());

            viewHolder.gameName.setText(dataBean.getName());
            viewHolder.money.setText("余额：￥" + dataBean.getMoney());

            if (game_id == dataBean.getGame_id()) {
                viewHolder.itemView.setBackgroundResource(R.drawable.textbackground);
            } else {
                viewHolder.itemView.setBackgroundResource(R.drawable.textbackground5);
            }

        }

        @Override
        public int getItemCount () {
            return dataBeans.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            private TextView gameName;
            private TextView money;
            private View touchView;

            public ViewHolder (@NonNull View itemView) {
                super(itemView);
                gameName = itemView.findViewById(R.id.textView_Item_Third_Name);
                money = itemView.findViewById(R.id.textView_Item_Third_Money);
                touchView = itemView.findViewById(R.id.view_Item_Third_Press);
                touchView.setOnClickListener(onClickListener);
            }

            private View.OnClickListener onClickListener = new View.OnClickListener() {
                @Override
                public void onClick (View v) {
                    game_id = (int) v.getTag();
                    for (int i = 0; i < dataBeans.size(); i++) {
                        if (dataBeans.get(i).getGame_id() == game_id) {
                            m_GameName = dataBeans.get(i).getName();
                            break;
                        }
                    }
                    if(onItemClickListener != null){
                        onItemClickListener.onItem(game_id);
                    }
                    notifyDataSetChanged();
                }
            };
        }

        public void setOnItemClickListener (OnItemClickListener onItemClickListener) {
            this.onItemClickListener = onItemClickListener;
        }

        public interface OnItemClickListener {
            public void onItem (int game_id);
        }
    }

}
